/**
 * @desc 封装微信工具 - 网络请求
 * @author chend
 */
const Base64 = require('../utils/base64');
const {loginApi} = require('../apiConfig/apiList/luban')
class Http {
  constructor() {
    this.requestCount = 0,
    this.isRelogin = {show: false}
  }
  
  encodeToken(){
    let token = wx.getStorageSync('loginData').authToken || '';
    return token;
  }

  /**
   * 网络状态码处理
   * @param {*} code
   * @param {*} message
   */
  interceptors(resolve, reject, res) {
    console.log('res', res);
    const { data } = res
    if ((Number(data.code)) !== 200) {
      console.log('data', data);
      this.errorHandler(reject, data)
      return new Promise(resolve, reject).then(()=>{
        resolve(true);
      }).catch(()=>{
        reject(data)
      })
    } else {
      this.hideLoading()
      resolve(res)
    }
  }

  /**
   * 接口请求错误处理
   * @param {Promise} reject
   * @param {*} err
   */
  errorHandler(reject, err) {
    this.hideLoading()
    if(err.code == 505){
      wx.login({
        success: (res) => {
          let code = res.code;
          loginApi({code}).then(lRes => {
            let data = lRes.data;
            let page = getCurrentPages().pop().route;
            if(lRes.code !== 200) {return}
            const { loginType = '', maOpenId, maSessionKey, maUnionId, toBind, authToken = '',schoolName = '' ,loginUser, subscribeStatus = '' } = data;
            wx.setStorageSync('loginData', {loginType, maOpenId, maSessionKey, maUnionId, toBind, authToken,schoolName, loginUser, subscribeStatus })
            wx.redirectTo({
              url: '/' + page,
            })
          });
        }
      });
    }else{
      wx.showToast({
        title: err.msg,
        icon: 'none',
        mask: true,
        success: () => {
          reject(err)
        }
      })
    }
  }

  showLoading() {
    this.requestCount++;
    if (this.requestCount === 1) {
      wx.showLoading({
        title: '加载中...',
        mask: true
      })
    }
  }

  hideLoading() {
    this.requestCount--;
    if (this.requestCount === 0) {
      wx.hideLoading()
    }
  }

  /**
   * 去除空参数
   */
  removeEmptyParam(object) {
    for (let o in object) {
      if (['', undefined, 'undefined', null, 'null'].includes(object[o])) {
        delete object[o]
      }
    }
    return object
  }

  /**
   * GET请求
   * @param {*} url - 请求url
   * @param {*} params - 请求数据
   */
  get(url, params) {
    this.showLoading()
    return new Promise((resolve, reject) => {
      wx.request({
        url: url,
        data: params,
        method: 'GET',
        header: {
          token: this.encodeToken(),
          'content-type': 'application/json; charset=utf-8' // 默认值
        },
        success: res => this.interceptors(resolve, reject, res),
        fail: err => this.errorHandler(reject, err)
      })
    })
  }
  /**
   * POST请求
   * @param {*} url - 请求url
   * @param {*} params - 请求数据
   */
  post(url, data, contentType = 'application/json; charset=utf-8') {
    this.showLoading()
    return new Promise((resolve, reject) => {
      // data = this.removeEmptyParam(data)
      wx.request({
        url: url,
        data: data,
        method: 'POST',
        header: {
          Accept: 'application/json',
          token: this.encodeToken(),
          'content-type': contentType
        },
        success: res => this.interceptors(resolve, reject, res),
        fail: err => this.errorHandler(reject, err)
      })
    })
  }

  /**
   * 使用默认header的请求
   * @param {} url
   * @param {*} data
   */
  request(url, data) {
    this.showLoading()
    return new Promise((resolve, reject) => {
      wx.request({
        url,
        data,
        success: res => this.interceptors(resolve, reject, res),
        fail: err => this.errorHandler(reject, err)
      })
    })
  }
}

export default new Http()
